package com.hsgene.order.service.impl;

import com.hsgene.common.util.basic.UUID32;
import com.hsgene.common.util.character.CharactersConstant;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.generator.constants.GeneratorEnum;
import com.hsgene.generator.dto.GeneratorDto;
import com.hsgene.order.persistence.ApplyOrderRepository;
import com.hsgene.order.service.ApplyOrderService;
import com.hsgene.order.service.api.GeneratorService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 申请单
 *
 * @author wxf
 * @date 2018/9/21 17:06
 **/
@Service
public class ApplyOrderServiceImpl implements ApplyOrderService {

    @Resource
    private ApplyOrderRepository applyOrderRepository;

    @Resource
    private GeneratorService generatorService;

    /**
     * 新增申请单编号
     *
     * @param orderId   订单ID
     * @param agencyIds 机构ids
     */
    @Override
    public String addApplyOrder(String orderId, String agencyIds) {
        //agencyIds为空,说明不同套餐寄送不同机构;不为空,则所有套餐寄送同一机构
        Date createTime = new Date();
        if (StringUtils.isEmpty(agencyIds)) {
            agencyIds = applyOrderRepository.getAgencyId(orderId);
            if (StringUtils.isEmpty(agencyIds)) {
                return "监测机构不存在";
            }
            //对机构去重处理
            List<String> agencyList = getAgencyList(agencyIds);
            for (String agencyId : agencyList) {
                String applyNo = getOrderNo("apply_order");
                applyOrderRepository.addApplyOrder(agencyId, orderId, applyNo, createTime);
            }
        } else {
            String applyNo = getOrderNo("apply_order");
            List<String> agencyList = getAgencyList(agencyIds);
            for (String agencyId : agencyList) {
                applyOrderRepository.addApplyOrder(agencyId, orderId, applyNo, createTime);
            }
        }
        return null;
    }

    private List<String> getAgencyList(String agencyIds) {
        return Arrays.asList(agencyIds.split(CharactersConstant.COMMA_EN)).stream().distinct()
                .collect(Collectors.toList());
    }

    private String getOrderNo(String type) {
        ApiResult<GeneratorDto> generatorResult = generatorService.numberGenerator(GeneratorEnum.GTON.getType(),0,0);
        if (generatorResult.isSucc()) {
            return generatorResult.getData().getSerialNumber();
        }
        return getUUID32();
    }

    private String getUUID32() {
        return UUID32.randomUUIDString();
    }

}
